package com.example.qxfw.dysjrh.service.impl;

import cn.hutool.core.io.FileUtil;
import com.example.qxfw.common.DbConfig;
import com.example.qxfw.common.service.FileRequestService;
import com.example.qxfw.common.util.GetPath;
import com.example.qxfw.dysjrh.config.DmgisConfig;
import com.example.qxfw.dysjrh.dto.RadarDto;
import com.example.qxfw.dysjrh.entity.LdPngFile;
import com.example.qxfw.dysjrh.entity.vo.RadarVo;
import com.example.qxfw.dysjrh.mapper.RadarMapper;
import com.example.qxfw.dysjrh.mapper.RaidenMapper;
import com.example.qxfw.dysjrh.service.RadarService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.datetime.joda.LocalDateTimeParser;
import org.springframework.stereotype.Service;

import com.example.qxfw.dysjrh.service.RadarService;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.time.LocalDateTime;

import java.time.format.DateTimeFormatter;
import java.util.*;

@Slf4j
@Service
@RequiredArgsConstructor
public class RadarServiceImpl implements RadarService {

    private final RadarMapper radarMapper;

    private final DmgisConfig dmgisConfig;

    @Qualifier("mongoPrimaryTemplate")
    @Autowired
    private MongoTemplate mongoTemplate;

    private final FileRequestService fileRequestService;


    @Override
    public List<RadarVo> getRadarData(RadarDto radarDto) {

        // 检查输入参数是否为空
        if (radarDto == null) {
            throw new IllegalArgumentException("RadarDto cannot be null");
        }

        // 获取雷达数据的各个参数
        LocalDateTime startTime = radarDto.getStartTime();
        LocalDateTime endTime = radarDto.getEndTime();
        //实例测试：测试时间
//        startTime = LocalDateTime.parse("2025-01-01 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//        endTime = LocalDateTime.parse("2025-01-10 23:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); // 修改了这里

        String stationid = radarDto.getStationid();
        String ldtype = radarDto.getLdtype();
        Double elevation = radarDto.getElevation();

        // 添加日志记录，便于调试
        log.debug("Fetching radar data with parameters: startTime={}, endTime={}, stationid={}, ldtype={}, elevation={}",
                startTime, endTime, stationid, ldtype, elevation);

        try {
            // 调用 Mapper 方法获取雷达数据
            List<RadarVo> radarVoList = radarMapper.getRadarData(startTime, endTime, stationid, ldtype, elevation);
            for (RadarVo radarVo : radarVoList) {
                String time = radarVo.getDatechar().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                // 查询mongodb中的图片地址

//                Query query = new Query();
                Double ele = radarVo.getElevation();
                String elevationStr = formatNumber(ele);

                // 添加第一个条件
//                query.addCriteria(Criteria.where("elevation").is("5"));//（实例，可用于测试是否能拿到mongo中的文件）
//                query.addCriteria(Criteria.where("stationid").is("403"));
//                query.addCriteria(Criteria.where("ldtype").is("R20"));
//                query.addCriteria(Criteria.where("timechar").is("0430"));
//                query.addCriteria(Criteria.where("dateyear").is("2025"));
//                query.addCriteria(Criteria.where("datechar").is("2025-01-09"));

//                query.addCriteria(Criteria.where("elevation").is(radarVo.getElevation().toString()));//bug:局数库中的为5而不是5.0导致查不到。


//                query.addCriteria(Criteria.where("elevation").is(elevationStr));
//                query.addCriteria(Criteria.where("ldtype").is(radarVo.getLdtype()));
//                query.addCriteria(Criteria.where("stationid").is(radarVo.getStationid()));
//                query.addCriteria(Criteria.where("timechar").is(radarVo.getTimechar()));
//                query.addCriteria(Criteria.where("dateyear").is(radarVo.getDatayear().toString()));
//                query.addCriteria(Criteria.where("datechar").is(time));
//                LdPngFile pngFile = mongoTemplate.findOne(query, LdPngFile.class);
//                System.out.println(pngFile);
//                System.out.println("-----------");
//
//                if (pngFile == null) continue;
//                // 根据图片url生成图片名字
//                String imageName = pngFile.get_id();
//                String fileName = dmgisConfig.getTxtFilePath() + imageName + ".png";
//                radarVo.setImagePath(dmgisConfig.getNgfileUrl() + imageName + ".png");
//                // 删除文件
//                FileUtil.del(fileName);
//                //创建文件
//                FileUtil.touch(fileName);
//                FileUtil.writeBytes(pngFile.getData(), new File(fileName));

                Map<String, Object> queryMap = new HashMap<>();
                queryMap.put("collectionName", "ld_png_file");
                queryMap.put("datechar", time);
                queryMap.put("timechar", radarVo.getTimechar());
                queryMap.put("ldtype", radarVo.getLdtype());
                queryMap.put("elevation", elevationStr);
                queryMap.put("stationid", radarVo.getStationid());
                queryMap.put("advCode", "");

//                Map<String, Object> queryMap = new HashMap<>();
//                queryMap.put("collectionName", "ld_png_file");
//                queryMap.put("datechar", "2025-01-14");
//                queryMap.put("timechar", "1645");
//                queryMap.put("ldtype", "R20");
//                queryMap.put("elevation", "0.9");
//                queryMap.put("stationid", "403");
//                queryMap.put("advCode", "");




//                String path = selectPath(queryMap);
                byte[] bytes = fileRequestService.selectData(queryMap);


                String path2 = "DmgisPubData/dmgis_xjservice_file/ld_png_file" + "/" + time + "/" + radarVo.getTimechar() + "/" + radarVo.getLdtype() + "/" + elevationStr + "/" + radarVo.getStationid() + ".png";
//                String path2 = "DmgisPubData/dmgis_xjservice_file/ld_png_file" + "/" + "2025-01-14" + "/" + "1645" + "/" + "R20" + "/" + "0.9" + "/" + "403" + ".png";


                String fileName = dmgisConfig.getTxtFilePath() + path2 ;
                //删除文件
                FileUtil.del(fileName);
                //创建文件
                FileUtil.touch(fileName);
                FileUtil.writeBytes(bytes, new File(fileName));

                String imagePath = dmgisConfig.getNgfileUrl() + path2;

                radarVo.setImagePath(imagePath);

            }
            return radarVoList;
        } catch (Exception e) {
            // 捕获并记录异常
            log.error("Failed to fetch radar data", e);
            throw new RuntimeException("Failed to fetch radar data", e);
        }
    }

    public static String formatNumber(double number) {
        String str = String.valueOf(number);
        if (str.matches("\\d+\\.0+")) {
            // 如果是整数，去掉小数点
            return str.split("\\.")[0];
        } else {
            // 如果是小数，直接保留小数部分
            return str;
        }
    }


    public String selectPath(Map<String, Object> queryMap) {
//        String dbName = DbConfig.dbname;
        String dbName = dmgisConfig.getDbname();
        String collectionName = (String)queryMap.get("collectionName");
        queryMap.remove("collectionName");
//        if (!StringUtil.IsNullOrEmpty((String)queryMap.get("advCode"))) {
        String advCode = (String)queryMap.get("advCode");
        if (Objects.nonNull(advCode) && !advCode.isEmpty()) {
            dbName = dbName + "_" + queryMap.get("advCode");
            queryMap.remove("advCode");
        }

//        String basePath = GettqFilepath();
        String basePath = dmgisConfig.getWinpath();
        String filePath = basePath  +  "DmgisPubData" + File.separator + dbName + File.separator + collectionName + File.separator;
        filePath = GetPath.action(queryMap, filePath, collectionName);
        return filePath;
    }


    private String GettqFilepath() {
        String tqFilepath = "";
        String os = System.getProperty("os.name").toLowerCase();
        if (os.contains("win")) {
            tqFilepath = DbConfig.winpath;
        } else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
            tqFilepath = DbConfig.linuxpath;
        }
        return tqFilepath;
    }


}
